<template>
  <div class="order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-title">
        <i class="el-icon-tickets"></i>
        我的订单
      </div>
      <div class="header-filter">
        <el-select
          v-model.number="filter"
          placeholder="筛选订单类型"
          size="large"
          @change="reLoadData"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.title"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>

    <!-- 订单内容 -->
    <div class="order-content">
      <!-- 空状态 -->
      <div v-if="tableData.length === 0" class="empty-order">
        <div class="empty-icon">
          <i class="el-icon-document"></i>
        </div>
        <div class="empty-text">暂无订单</div>
        <div class="empty-desc">去商城逛逛，选购心仪的商品</div>
        <el-button type="primary" @click="$router.push('/')">
          去购物
        </el-button>
      </div>

      <!-- 订单列表 -->
      <div v-else class="order-list">
        <div
          v-for="(order, index) in tableData"
          :key="order.id"
          class="order-card"
        >
          <!-- 订单头部 -->
          <div class="order-header">
            <div class="order-info">
              <span class="order-number">订单编号：{{ order.id }}</span>
              <span class="order-time"
                >下单时间：{{ formatTime(order.created_at) }}</span
              >
            </div>
            <div class="order-status">
              <span class="status-tag" :class="getStatusClass(order.state)">
                {{ getStatusText(order.state) }}
              </span>
            </div>
          </div>

          <!-- 订单商品 -->
          <div class="order-goods">
            <div
              v-for="item in order.goods"
              :key="item.item.id"
              class="goods-item"
            >
              <div class="goods-image">
                <el-image :src="item.item.image" fit="cover" class="goods-img">
                  <template #error>
                    <div class="image-error">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="goods-info">
                <div class="goods-name">{{ item.item.name }}</div>
                <div class="goods-desc">{{ item.item.description }}</div>
                <div class="goods-spec">
                  <span class="goods-brand">{{ item.item.brand }}</span>
                  <span class="goods-category">{{
                    item.item.category.name
                  }}</span>
                </div>
              </div>
              <div class="goods-price">
                <div class="price-current">
                  ¥{{ item.item.discounted_price }}
                </div>
                <div
                  class="price-original"
                  v-if="item.item.price > item.item.discounted_price"
                >
                  ¥{{ item.item.price }}
                </div>
              </div>
              <div class="goods-quantity">
                <span class="quantity-text">×{{ item.count }}</span>
              </div>
              <div class="goods-total">
                <div class="total-price">
                  ¥{{ (item.item.discounted_price * item.count).toFixed(2) }}
                </div>
              </div>
            </div>
          </div>

          <!-- 订单汇总 -->
          <div class="order-summary">
            <div class="summary-left">
              <div class="address-info">
                <i class="el-icon-location"></i>
                {{ order.address }}
              </div>
            </div>
            <div class="summary-right">
              <div class="price-info">
                <div class="price-item">
                  <span>商品总价：</span>
                  <span>¥{{ order.price }}</span>
                </div>
                <div class="price-item save" v-if="order.save_price > 0">
                  <span>节省金额：</span>
                  <span>¥{{ order.save_price }}</span>
                </div>
                <div class="price-item total">
                  <span>实付金额：</span>
                  <span class="total-amount">¥{{ order.price }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 订单操作 -->
          <div class="order-actions">
            <div class="action-left">
              <!-- 预留其他操作 -->
            </div>
            <div class="action-right">
              <el-button
                :type="stateMap[order.state].type"
                @click="clickOrder(index)"
                class="action-btn"
                :class="getActionBtnClass(order.state)"
              >
                {{ stateMap[order.state].title }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div v-show="hasMore" class="load-more" @click="loadData">
        <el-button type="text" :loading="loadingMore">
          {{ loadingMore ? "加载中..." : "点击加载更多" }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { RequestPath, startRequest } from "../base/RequestWork";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import Account from "../base/AccountStore";

let router = useRouter();
// 订单列表数据
let tableData = ref<any[]>([]);
let account = Account();
// 是否有更多数据
let hasMore = ref(true);
// 订单筛选条件
let filter = ref(-1);
// 分页数据
let limit = 4;
// 存储订单状态与按钮类型的
let stateMap = [
  {
    title: "已付款",
    type: "info",
  },
  {
    title: "已发货，确认收货",
    type: "primary",
  },
  {
    title: "已收货，前往评价",
    type: "success",
  },
  {
    title: "已完成",
    type: "info",
  },
];
// 存储筛选项
let options = [
  {
    title: "全部",
    value: -1,
  },
  {
    title: "已付款",
    value: 0,
  },
  {
    title: "已发货",
    value: 1,
  },
  {
    title: "已收货",
    value: 2,
  },
  {
    title: "已完成",
    value: 3,
  },
];

// 新增状态
let loadingMore = ref(false);

// 新增方法
const formatTime = (timeStr: string) => {
  return new Date(timeStr).toLocaleString();
};

const getStatusText = (state: number) => {
  const statusMap = ["待发货", "待收货", "待评价", "已完成"];
  return statusMap[state] || "未知状态";
};

const getStatusClass = (state: number) => {
  const classMap = ["waiting", "shipping", "received", "completed"];
  return classMap[state] || "unknown";
};

const getActionBtnClass = (state: number) => {
  const classMap = [
    "btn-waiting",
    "btn-shipping",
    "btn-received",
    "btn-completed",
  ];
  return classMap[state] || "";
};

// 组件加载时请求订单数据
onMounted(() => {
  // 检查是否登录
  if (!account.isLogin) {
    ElMessage.warning("请先登录后再查看订单");
    router.push({
      name: "login",
    });
    return;
  }

  reLoadData();
});

// 刷新数据
function reLoadData() {
  tableData.value = [];
  loadData();
}

// 加载数据
function loadData() {
  loadingMore.value = true;
  let params: any = {
    limit,
    offset: tableData.value.length,
    type: 1,
  };
  if (filter.value >= 0) {
    params.filter = filter.value;
  }
  startRequest(RequestPath.orderListGet, "get", params)
    .then((response) => {
      // 使用更安全的数据访问方式
      let orders = [];
      if (response.data && response.data.data && response.data.data.orders) {
        orders = response.data.data.orders;
      } else if (response.data && response.data.datas) {
        // 如果数据结构是 datas 而不是 data.orders
        orders = response.data.datas;
      } else if (response.data && Array.isArray(response.data)) {
        // 如果直接返回数组
        orders = response.data;
      }

      hasMore.value = orders.length >= limit;
      // 对属性进行赋值
      tableData.value.push(...orders);
    })
    .catch((error) => {
      ElMessage.error({
        message: error.response?.data?.error || "加载订单数据失败",
      });
    })
    .finally(() => {
      loadingMore.value = false;
    });
}

// 对订单进行操作
function clickOrder(index: number) {
  let order = tableData.value[index];
  if (order.state == 1) {
    // 确认收货操作
    startRequest(RequestPath.orderUpdate, "get", {
      oid: order.id,
      state: 2,
    })
      .then(() => {
        order.state = 2;
      })
      .catch((error) => {
        ElMessage.error({
          message: error.response?.data?.error || "确认收货失败",
        });
      });
  } else if (order.state == 2) {
    // 去评价
    router.push({
      name: "evaluation",
      params: { order: order.id },
    });
  }
}
</script>

<style scoped>
.order-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 30px;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 700;
  color: #333;
}

.header-title i {
  margin-right: 10px;
  color: #409eff;
  font-size: 28px;
}

.header-filter {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 空状态 */
.empty-order {
  text-align: center;
  padding: 80px 0;
}

.empty-icon {
  font-size: 80px;
  color: #ccc;
  margin-bottom: 20px;
}

.empty-text {
  font-size: 18px;
  color: #666;
  margin-bottom: 10px;
}

.empty-desc {
  font-size: 14px;
  color: #999;
  margin-bottom: 30px;
}

/* 订单卡片 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  transition: box-shadow 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-number {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-status {
  display: flex;
  align-items: center;
}

.status-tag {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.waiting {
  background: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.status-tag.shipping {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-tag.received {
  background: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.status-tag.completed {
  background: #f6f6f6;
  color: #999;
  border: 1px solid #e8e8e8;
}

/* 订单商品 */
.order-goods {
  padding: 20px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f8f8f8;
  gap: 15px;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 80px;
  height: 80px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
}

.goods-img {
  width: 100%;
  height: 100%;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #ccc;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
  line-height: 1.4;
}

.goods-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2; /* 添加标准属性 */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.goods-spec {
  display: flex;
  gap: 10px;
}

.goods-brand,
.goods-category {
  font-size: 12px;
  color: #999;
  padding: 2px 8px;
  background: #f5f5f5;
  border-radius: 4px;
}

.goods-price {
  text-align: center;
  min-width: 80px;
}

.price-current {
  font-size: 16px;
  color: #ff4444;
  font-weight: 500;
  margin-bottom: 5px;
}

.price-original {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.goods-quantity {
  text-align: center;
  min-width: 60px;
}

.quantity-text {
  color: #666;
  font-size: 14px;
}

.goods-total {
  text-align: center;
  min-width: 100px;
}

.total-price {
  font-size: 16px;
  color: #ff4444;
  font-weight: 500;
}

/* 订单汇总 */
.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  background: #f8f9fa;
  border-top: 1px solid #f0f0f0;
}

.address-info {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.address-info i {
  margin-right: 5px;
  color: #409eff;
}

.price-info {
  text-align: right;
}

.price-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
  min-width: 200px;
}

.price-item.save {
  color: #52c41a;
}

.price-item.total {
  border-top: 1px solid #e0e0e0;
  padding-top: 8px;
  margin-top: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.total-amount {
  color: #ff4444;
  font-weight: 700;
}

/* 订单操作 */
.order-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

.action-right {
  display: flex;
  gap: 10px;
}

.action-btn {
  padding: 8px 20px;
  border-radius: 4px;
  font-weight: 500;
}

.btn-waiting {
  background: #1890ff;
  border-color: #1890ff;
}

.btn-shipping {
  background: #52c41a;
  border-color: #52c41a;
}

.btn-received {
  background: #fa8c16;
  border-color: #fa8c16;
}

.btn-completed {
  background: #f0f0f0;
  border-color: #f0f0f0;
  color: #999;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 30px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .goods-item {
    flex-wrap: wrap;
    gap: 10px;
  }

  .order-summary {
    flex-direction: column;
    gap: 15px;
  }

  .price-info {
    text-align: left;
    width: 100%;
  }

  .order-actions {
    flex-direction: column;
    gap: 15px;
    align-items: flex-end;
  }
}
</style>